package com.zzyl.nursing.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.HistoryDeviceDataMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component("deleteTask")
public class DeleteTask {


    @Resource
    private DeviceDataMapper deviceDataMapper;


    @Resource
    private HistoryDeviceDataMapper historyDeviceDataMapper;

    /**
     * 删除10分钟前的设备数据，并将其历史记录插入到历史数据表中。
     *
     * @throws Exception 如果在删除或插入数据过程中出现异常。
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteDeviceData() {
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.le(DeviceData::getAlarmTime, LocalDateTime.now().plusMinutes(-10));
        List<DeviceData> list = deviceDataMapper.selectList(queryWrapper);
        if (list != null && list.size() > 0) {
            for (DeviceData deviceData : list) {
                try {
                    historyDeviceDataMapper.insertDeviceData(deviceData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        for (DeviceData deviceData : list) {
            Long id = deviceData.getId();
            deviceDataMapper.deleteDeviceDataById(id);
        }


    }

}
